<!DOCTYPE html>
<html ng-app="MyAPP">
<head>
    <meta charset="utf-8">
    <title>AngularJS&middot;Hello AngularJS</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.css">
    <style>
        .demo{
            margin-bottom:10px;
        }
    </style>
</head>
<body>

 <div class="container">
     <div class="row">
         <nav class="navbar navbar-default navbar-static-top">
             <div class="container-fluid">
                 <div class="navbar-header">
                     <a class="navbar-brand" href="../index.html">首页</a>
                 </div>
                 <ul class="nav navbar-nav">
                    <li class="active"><a href="javascript:void(0)">Link</a></li>
                    <li><a href="javascript:void(0)">Link2</a></li>
                 </ul>
             </div>
         </nav>
     </div>
     <div class="row demo">
         <h3>添加、删除输入框并计算总值</h3>
         <div ng-controller="NumCalculateCtrl">
             <div ng-repeat="(index,item) in items track by $index">   <!-- 借助track by $index进行循环，避免items中出现重复的值-->
                 <p><input ng-model="items[index]"/><button ng-click="Fn.del(index)">删除</button></p>
             </div>
             <p>
                 {{result}}
             </p>
             <button ng-click="Fn.add()">Add</button>
             <button ng-click="getResult()">Result</button>
         </div>

     </div>
 </div>
 </div>
</body>
</html>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.js" type="text/javascript"></script>
<script>
    var app=angular.module("MyAPP",[]);
    app.controller("NumCalculateCtrl",function($scope){
        $scope.items=[];//用户存储分配的ng-model对象
        $scope.getResult=function(){
            var result=0;
            angular.forEach($scope.items,function(item,index){
                console.log(item);
                result+=parseInt($scope.items[index]);
            });
            $scope.result=result;
        }
        var i=0; //索引计数器
        $scope.Fn={
            add:function(){
                $scope.items[i]=0;
                i++;
            },
            del:function(index){
                console.log(index);
                $scope.items.splice(index,1);
                i--;
                $scope.getResult();
            }
        }
    });
</script>
